﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;

namespace StudentInfoSystem.UI.Views.Dialogs
{
    public partial class ProgressDialog : Window
    {
        private bool _isCompleted = false;
        private DispatcherTimer _autoCloseTimer;

        public string Message
        {
            get => MessageText.Text;
            set => MessageText.Text = value;
        }

        public bool CanCancel
        {
            get => CancelButton.Visibility == Visibility.Visible;
            set => CancelButton.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
        }

        public event EventHandler CancelRequested;

        public ProgressDialog()
        {
            InitializeComponent();
            Closing += OnClosing;
            Topmost = true; // 确保对话框在顶层
        }

        // 添加新的构造函数重载，确保位置正确
        public ProgressDialog(Window owner) : this()
        {
            Owner = owner;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
        }

        public new void Close()
        {
            if (Dispatcher.CheckAccess())
            {
                base.Close();
            }
            else
            {
                Dispatcher.Invoke(() => base.Close());
            }
        }

        private void OnClosing(object sender, CancelEventArgs e)
        {
            if (!_isCompleted && !CanCancel)
            {
                e.Cancel = true;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            CancelRequested?.Invoke(this, EventArgs.Empty);
            Close();
        }

        // 静态方法用于创建和显示进度对话框
        public static ProgressDialog Show(string title, string message, bool canCancel = false, Window owner = null)
        {
            ProgressDialog dialog;

            // 使用新的构造函数确保居中
            if (owner != null)
            {
                dialog = new ProgressDialog(owner)
                {
                    Title = title,
                    Message = message,
                    CanCancel = canCancel
                };

                // 设置主窗口不可交互
                owner.IsEnabled = false;
            }
            else
            {
                dialog = new ProgressDialog
                {
                    Title = title,
                    Message = message,
                    CanCancel = canCancel,
                    WindowStartupLocation = WindowStartupLocation.CenterScreen
                };
            }

            // 确保对话框正确显示在父窗口上方
            if (owner != null && owner.IsVisible)
            {
                dialog.Show();
            }
            else
            {
                dialog.Show();
            }

            return dialog;
        }

        // 确保对话框在显示时正确居中
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            // 如果设置了Owner，但位置不是中心，强制居中
            if (Owner != null && WindowStartupLocation != WindowStartupLocation.CenterOwner)
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner;
            }
        }

        // 完成进度后关闭对话框
        public void Complete(string successMessage = "操作已完成")
        {
            Dispatcher.Invoke(() =>
            {
                _isCompleted = true;

                ProgressBarControl.Style = null;
                ProgressBarControl.Value = 100;
                ProgressBarControl.IsIndeterminate = false;

                Message = successMessage;
                CancelButton.Visibility = Visibility.Collapsed;

                StartAutoCloseTimer(1, successMessage);
            });
        }

        // 报告错误并关闭对话框
        public void ReportError(string errorMessage)
        {
            Dispatcher.Invoke(() =>
            {
                _isCompleted = true;

                ProgressBarControl.Style = null;
                ProgressBarControl.Foreground = System.Windows.Media.Brushes.Red;
                ProgressBarControl.Value = 100;

                Message = errorMessage;
                CancelButton.Visibility = Visibility.Collapsed;

                StartAutoCloseTimer(3, errorMessage);
            });
        }

        // 统一的定时器关闭方法
        private void StartAutoCloseTimer(int seconds, string message)
        {
            if (_autoCloseTimer != null)
            {
                _autoCloseTimer.Stop();
                _autoCloseTimer = null;
            }

            _autoCloseTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(seconds)
            };

            _autoCloseTimer.Tick += (s, e) =>
            {
                _autoCloseTimer.Stop();
                _autoCloseTimer = null;

                if (Owner != null)
                {
                    Owner.IsEnabled = true;
                    Owner.Activate();
                }

                Close();
            };

            _autoCloseTimer.Start();
        }

        protected override void OnClosed(EventArgs e)
        {
            if (_autoCloseTimer != null)
            {
                _autoCloseTimer.Stop();
                _autoCloseTimer = null;
            }

            if (Owner != null && !Owner.IsEnabled)
            {
                Owner.IsEnabled = true;
                Owner.Activate();
            }

            base.OnClosed(e);
        }
    }
}